package com.xcjh.googlemix

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.games.PlayGames.getLeaderboardsClient
import com.google.android.gms.wallet.*
import com.google.firebase.analytics.FirebaseAnalytics
import com.xcjh.base_lib.Constants
import com.xcjh.base_lib.base.activity.BaseActivity
import com.xcjh.base_lib.route.RouteCenter
import com.xcjh.googlemix.databinding.ActivityCheckoutBinding
import com.xcjh.googlemix.viewmodel.CheckoutViewModel
import org.json.JSONException
import org.json.JSONObject

/**
 * Checkout implementation for the app
 */
class CheckoutActivity : BaseActivity() {

    // Arbitrarily-picked constant integer you define to track a request for payment data activity.
    private val loadPaymentDataRequestCode = 991

    private val model: CheckoutViewModel by viewModels()

    private lateinit var layoutBinding: ActivityCheckoutBinding
    private lateinit var googlePayButton: View

    /**
     * 在创建活动时初始化 Google Pay API
     *
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FirebaseAnalytics.getInstance(this)
        // Use view binding to access the UI elements
        layoutBinding = ActivityCheckoutBinding.inflate(layoutInflater)
        setContentView(layoutBinding.root)

        googlePayButton = layoutBinding.googlePayButton.root
        layoutBinding.googleLogin.setOnClickListener {
            //DoLogin()
            RouteCenter.navigate(Constants.Router.Ad.A_Ad_MAIN)
        }
        googlePayButton.visibility=View.VISIBLE
        googlePayButton.setOnClickListener {
            //requestPayment()

            RouteCenter.navigate(Constants.Router.Login.A_Login_MAIN)
        }

        // Check whether Google Pay can be used to complete a payment
       // model.canUseGooglePay.observe(this, Observer(::setGooglePayAvailable))
       // Initialize(this)
    }

    /**
     * 如果 isReadyToPay 返回“true”，则显示按钮并隐藏“正在检查”文本。
     * 否则，通知用户 Google Pay 不可用。请调整以适应您当前的用户流程。
     * 如果 isReadyToPay 返回“false”，您无需明确告知用户。
     *
     * @param available isReadyToPay API response.
     */
    private fun setGooglePayAvailable(available: Boolean) {
        if (available) {
            googlePayButton.visibility = View.VISIBLE
        } else {
            Toast.makeText(this, "很遗憾，此设备不支持 Google Pay", Toast.LENGTH_LONG).show()
        }
    }

    private fun requestPayment() {

        // Disables the button to prevent multiple clicks.
        googlePayButton.isClickable = false

        // The price provided to the API should include taxes and shipping.
        // This price is not displayed to the user.
        val dummyPriceCents = 100L
        val shippingCostCents = 900L
        val task = model.getLoadPaymentDataTask(dummyPriceCents + shippingCostCents)

        // Shows the payment sheet and forwards the result to the onActivityResult method.
        AutoResolveHelper.resolveTask(task, this, loadPaymentDataRequestCode)
    }

    /**
     * Handle a resolved activity from the Google Pay payment sheet.
     *
     * @param requestCode Request code originally supplied to AutoResolveHelper in requestPayment().
     * @param resultCode Result code returned by the Google Pay API.
     * @param data Intent from the Google Pay API containing payment or error data.
     * @see [Getting a result
     * from an Activity](https://developer.android.com/training/basics/intents/result)
     */
    @Suppress("Deprecation")
    // Suppressing deprecation until `registerForActivityResult` is available on the Google Pay API.
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            // Value passed in AutoResolveHelper
            loadPaymentDataRequestCode -> {
                when (resultCode) {
                    RESULT_OK ->
                        data?.let { intent ->
                            PaymentData.getFromIntent(intent)?.let(::handlePaymentSuccess)
                        }

                    RESULT_CANCELED -> {
                        // 用户取消了付款尝试
                        Toast.makeText(this, "用户取消了付款尝试", Toast.LENGTH_LONG).show()
                    }

                    AutoResolveHelper.RESULT_ERROR -> {
                        AutoResolveHelper.getStatusFromIntent(data)?.let {
                            handleError(it.statusCode)
                        }
                    }
                }

                // Re-enables the Google Pay payment button.
                googlePayButton.isClickable = true
            }
            100 -> {//登录
                val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data!!)
                if(result!!.isSuccess) {
                    //验证登入是否成功
                    Toast.makeText(this,"Google Play Login Success",Toast.LENGTH_LONG).show()
                    OpenRankingList()//登入成功进行排行榜打开
                } else{
                    Toast.makeText(this,"Google Play Login Failed,Code:${result.status.statusCode}",Toast.LENGTH_LONG).show()
                }
            }
            101 -> {//排行
                when (resultCode) {
                    RESULT_OK ->{

                    }
                    RESULT_CANCELED -> {

                    }
                }
            }

        }
    }

    /**
     * PaymentData 响应对象包含付款信息，以及任何其他请求的信息，例如帐单和送货地址。
     *
     * @param paymentData 付款人批准付款后，Google 返回的响应对象。
     * @see [Payment
     * Data](https://developers.google.com/pay/api/android/reference/object.PaymentData)
     */
    private fun handlePaymentSuccess(paymentData: PaymentData) {
        val paymentInformation = paymentData.toJson() ?: return

        try {
            // Token will be null if PaymentDataRequest was not constructed using fromJson(String).
            val paymentMethodData =
                JSONObject(paymentInformation).getJSONObject("paymentMethodData")
            val billingName = paymentMethodData.getJSONObject("info")
                .getJSONObject("billingAddress").getString("name")
            Log.d("BillingName", billingName)

            Toast.makeText(this, getString(R.string.payments_show_name, billingName), Toast.LENGTH_LONG).show()

            // Logging token string.
            Log.d("GooglePaymentToken", paymentMethodData.getJSONObject("tokenizationData").getString("token"))

        } catch (error: JSONException) {
            Log.e("handlePaymentSuccess", "Error: $error")
        }
    }

    /**
     * 在此阶段，用户已经看到一个弹出窗口，通知他们发生了错误。通常，只需要日志记录。
     *
     * @param statusCode will hold the value of any constant from CommonStatusCode or one of the
     * WalletConstants.ERROR_CODE_* constants.
     * @see [
     * Wallet Constants Library](https://developers.google.com/android/reference/com/google/android/gms/wallet/WalletConstants.constant-summary)
     */
    private fun handleError(statusCode: Int) {
        Log.w("loadPaymentData failed", "Error code: $statusCode")
    }

    private lateinit var mGoogleSignInClient: GoogleSignInClient
    //初始化mGoogleSignInClient
    fun Initialize(activity: Activity) {
        mGoogleSignInClient = GoogleSignIn.getClient (activity,
        GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
            .requestEmail()
            .build()
        )
        /**
         * DEFAULT_GAMES_SIGN_IN
         * 应用必须发布，添加测试账号
         * 应用签名设置等是否正确
         * 应用的app_id是否设置正确
         */
        mGoogleSignInClient = GoogleSignIn.getClient(activity,
            GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) //.requestIdToken(PackageConfig.google_server_id)
            //   .requestIdToken(getString(R.string.default_web_client_id))
            .requestIdToken("553910769113-5dpqougsjta1oirjvodd6s3315chig9d.apps.googleusercontent.com")
          ///  .requestIdToken("1089472342223-dunrdpbbmh4g2ugnbjm6lq5vkffh6mna.apps.googleusercontent.com")
            .requestEmail()
            .build())
    }

    fun CheckIsLogined(): Boolean {//判断是否已经登入过帐号
        if (GoogleSignIn.getLastSignedInAccount(this) != null) {
            return false
        }
        return false
    }
    //进行登入请求
    fun DoLogin() {
        if (!CheckIsLogined()) {
            startActivityForResult(mGoogleSignInClient.signInIntent, 100)
        }

    }
    //进行打开排行榜请求
    fun OpenRankingList() {
        if (CheckIsLogined()) {
            getLeaderboardsClient(this)
                .getLeaderboardIntent(getString(R.string.leaderboard_id))
               // .getLeaderboardIntent(getString(R.string.leaderboard_easy))
                .addOnSuccessListener { intent ->
                    startActivityForResult(intent, 101)
                }
        }

    }
    //更新玩家的分数
    fun UpdateRanking() {
        getLeaderboardsClient(this)
            .submitScore(getString(R.string.leaderboard_id), 1337)

    }


}